package com.more.offer.algorithm.ali;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author pinoc
 * @date 2021/8/9
 * @description
 */
public class UseApi {
	private static Map<String, API> map = new HashMap<>();
	public boolean invoke(String name){
		if (name.isEmpty()){
			return false;
		}
		synchronized (map){
			System.out.println(map.containsKey(name));
			// 第一次请求该命令
			if(!map.containsKey(name)){
				API api = new API();
				api.setTime(System.currentTimeMillis()/1000 + 10);
				api.setCount(1);
				map.put(name, api);
				return true;
			}else{
				API api = map.get(name);
				return api.isValid();
			}
		}
	}

	// 测试方法，线程里面请求10次同一个方法 method1
	public static Runnable getThread(){
		return ()->{
			for(int i = 0; i < 10; i ++){
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				UseApi useApi = new UseApi();
				System.out.println(useApi.invoke("method1"));
			}
		};
	}

	public static void main(String[] args) {
		ExecutorService executorService = Executors.newFixedThreadPool(10);
		// 开10个线程进行测试
		for (int i = 0; i < 10; i++) {
			executorService.submit(getThread());
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		executorService.shutdown();
	}
}
